<template>
  <div ref="echartsRef" :style="styleObject"></div>
</template>

<script>
import * as echarts from "echarts";
import { mapActions } from "vuex";

export default {
  name: "EChartsComponent",
  props: {
    options: Object,
  },
  data() {
    return {
      chart: null,
      selectedData: null, // 用于存储点击选中的数据（name）
      width: "100%", // 可以通过 props 外部传入，假设宽度为父容器的100%
    };
  },
  computed: {
    styleObject() {
      return {
        width: this.width,
        height: "350px", // 设置默认高度
        minWidth: "600px", // 设置最小宽度为600px
        maxWidth: "1000px", //设置最大宽度
      };
    },
  },

  mounted() {
    this.$nextTick(() => {
      if (
        this.$refs.echartsRef &&
        this.$refs.echartsRef.clientWidth > 0 &&
        this.$refs.echartsRef.clientHeight > 0
      ) {
        this.initECharts();
      } else {
        console.error(
          "Cannot initialize ECharts. Container dimensions are zero."
        );
      }
    });
  },
  methods: {
    ...mapActions(["setSelectedData"]),
    initECharts() {
      this.chart = echarts.init(this.$refs.echartsRef);
      this.chart.setOption(this.options);
      this.chart.on("click", this.onChartClick);
    },
    onChartClick(params) {
      console.log(params);
      this.selectedData = params.name;
      this.setSelectedData(this.selectedData);
      this.$emit("data-selected", this.selectedData);
      console.log("点击选中数据", this.selectedData);
    },
  },
  watch: {
    options: {
      deep: true,
      handler(newOptions) {
        if (this.chart) {
          this.chart.setOption(newOptions, true);
        }
      },
    },
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
};
</script>
